package org.example.struct.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liyishan
 * @date 2023/12/4 10:20
 * @apiNote
 */

public class Test00204CountPrimes {
    public static void main(String[] args) {
        System.out.println(countPrimes1(10));
    }

    public static int countPrimes(int n) {
        int[] isPrime = new int[n];
        Arrays.fill(isPrime,1);
        int ans = 0;
        for(int i = 2; i < n; i++){
            if(isPrime[i] == 1){
                ans++;
                if((long)i * i < n){
                    for(int j = i * i; j < n; j += i){
                        isPrime[j] = 0;
                    }
                }
            }
        }
        return ans;
    }

    public static int countPrimes1(int n) {
        List<Integer> primes = new ArrayList<Integer>();
        int[] isPrime = new int[n];
        Arrays.fill(isPrime,1);
        for(int i = 2; i < n; i++){
            if(isPrime[i] == 1){
                primes.add(i);
            }
            for(int j = 0; j<primes.size() && i * primes.get(j) < n; j++){
                isPrime[i * primes.get(j)] = 0;
                if(i % primes.get(j) == 0){
                    break;
                }
            }
        }
        return primes.size();
    }

    public static int test(int n) {
        int ans = 0;
        for(int i = 2; i < n; i++){
            ans += isPrime(i) ? 1 : 0;
        }
        return ans;
    }

    public static boolean isPrime(int x) {
        for (int i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }
}
